﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Net;
using Core.BOL;
using Core.DAL;
using Core.Extentions;
using Core.Utils;
using Elmah;

namespace Core.ScheduleTask
{
    public static class GenerateMail
    {
        public static void Proceed()
        {
            StatMailsRepository smr = null;
            MailToGenerateRepository mtgr = null;
            MailQueueRepository mqr = null;
            UsersRepository ur = null;
            SectionRepository sr = null;

            try
            {
                smr = new StatMailsRepository();
                mtgr = new MailToGenerateRepository();
                mqr = new MailQueueRepository();
                ur = null;
                sr = new SectionRepository();
                ur = new UsersRepository();

                string siteName = ConfigurationManager.AppSettings["SiteName"];
                Uri siteUrl = new Uri(ConfigurationManager.AppSettings["SiteUrl"]);
                string pageTitle = string.Empty;

                // Get mail to generate
                tMail_ToGenerate mail = mtgr.GetLatestMailToGenerate();

                if (mail != null)
                {
                    //Section
                    tSite_Section section = sr.GetSectionsById(mail.SID);

                    // Get Users
                    List<Guid> lUserId = ur.GetUserIdBySectionID(mail.SID);
                    List<aspnet_User> lUsers = ur.GetUsersByListID(lUserId);

                    // Insert stat mail
                    tMail_Stats_List sm = new tMail_Stats_List();
                    sm.ID = Guid.NewGuid();
                    sm.InsertDate = DateTime.Now.GetNowTimeByTimeZone();
                    sm.SID = mail.SID;
                    smr.AddMail(sm);
                    smr.Save();

                    mail.MID = sm.ID;
                    mtgr.Save();

                    int i = 0;
                    foreach (aspnet_User u in lUsers)
                    {
                        // Get Mail HTML
                        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(siteUrl.AbsoluteUri + section.SystemName.UppercaseFirst() + "/Mail/" + mail.Action + "/" + mail.ID.ToString() + "/" + u.UserId.ToString()));
                        request.Headers.Add("ScheduleTask", "true");

                        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                        if (response != null && response.StatusCode != HttpStatusCode.NoContent)
                        {
                            string mailText = string.Empty;
                            using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                            {
                                mailText = reader.ReadToEnd();
                            }

                            response.Close();
                            request.Abort();

                            pageTitle = (pageTitle == string.Empty) ? Mail.FetchTitleFromHTML(mailText) : pageTitle;

                            tMail_Queue mailQueue = new tMail_Queue();
                            mailQueue.EmailTo = u.Email;
                            mailQueue.EmailFrom = section.Email;
                            mailQueue.SenderName = section.Section.UppercaseFirst() + " - " + siteName.UppercaseFirst();
                            mailQueue.Text = mailText.AddUrlInHref(siteUrl).AddUrlInSrc(siteUrl);
                            mailQueue.Title = pageTitle;
                            mailQueue.InsertDate = DateTime.Now.GetNowTimeByTimeZone();

                            mqr.InsertMail(mailQueue);
                            mqr.Save();

                            i++;
                        }
                    }

                    // Update mail Stat
                    sm.Title = pageTitle;
                    sm.NumItemsSended = i;
                    smr.Save();
                }
            }
            catch (Exception ex)
            {
                ErrorLog.GetDefault(null).Log(new Error(ex));
            }
            finally
            {
                if (smr != null)
                {
                    smr.Dispose();
                }

                if (ur != null)
                {
                    ur.Dispose();
                }

                if (sr != null)
                {
                    sr.Dispose();
                }

                if (mtgr != null)
                {
                    mtgr.Dispose();
                }

                if (mqr != null)
                {
                    mqr.Dispose();
                }
            }
        }
    }
}
